sbiz.CleanSubject.elementCount = 0;
sbiz.CleanSubject.htmlPrefixID = "prefix";
sbiz.CleanSubject.box = "groupbox-container";
sbiz.CleanSubject.display = null;
sbiz.CleanSubject.heightDiff = 28;
sbiz.CleanSubject.beginHeight = null;
sbiz.CleanSubject.heightNotModifiedCounter = 0;

// Add a xul box to the dialog
sbiz.CleanSubject.Add = function(value)
{
    var addToBox = document.getElementById(sbiz.CleanSubject.box);
    document.getElementById("copySource").style.display = sbiz.CleanSubject.display;
    var copySource = document.getElementById("copySource");
    var newElement = copySource.cloneNode(true);
    newElement.setAttribute("id", sbiz.CleanSubject.htmlPrefixID + (++sbiz.CleanSubject.elementCount));
    var tBox = newElement.getElementsByTagName("textbox")[0];
    tBox.setAttribute("value", value);

    addToBox.appendChild(newElement);
    document.getElementById("copySource").style.display = "none";
    
    if (value.length <= 0)
    {
        sbiz.CleanSubject.SaveWindowHeight();
        sbiz.CleanSubject.RecalculateWindowHeight(sbiz.CleanSubject.heightDiff);
        tBox.focus();
    }
}

// Delete the xul box
sbiz.CleanSubject.Delete = function(ID)
{
    sbiz.CleanSubject.SaveWindowHeight();
    document.getElementById(sbiz.CleanSubject.box).removeChild(document.getElementById(ID));
    sbiz.CleanSubject.elementCount--;
    sbiz.CleanSubject.RecalculateWindowHeight(0 - sbiz.CleanSubject.heightDiff);
}

// Validate the input on focus lost and remove the splitter if available
// This also verifies the regex
sbiz.CleanSubject.ValidateInput = function(obj)
{
    try
    {
        if ((obj.value).indexOf(sbiz.CleanSubject.splitter) != -1)
        {
            obj.value = (obj.value).replace(sbiz.CleanSubject.splitter, "");
        }
        // Check for valid regex
        try
        {
            var regex = new RegExp(obj.value, "i"); 
        }
        catch(e)
        {
            var extnamestrings = document.getElementById('extname-strings');
            var warning = extnamestrings.getString("extensions.cleansubject@style-biz.de.alertWrongRegex");
            warning = warning.replace("{0}", obj.value);
            alert(warning);
        }
    }
    catch (e)
    {
    }
}

// Load the preferences and add a xul box for each element
sbiz.CleanSubject.LoadPreferences = function() 
{
    // Save the display property of the copy source and hide it afterwards
    sbiz.CleanSubject.display = document.getElementById("copySource").style.display;
    document.getElementById("copySource").style.display = "none";

    sbiz.CleanSubject.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    
    // Get the prefixes
    var _prefixes = sbiz.CleanSubject.Trim(
            sbiz.CleanSubject.prefs.getCharPref(
                sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringPrefixes));
    sbiz.CleanSubject.prefixes = _prefixes.split(sbiz.CleanSubject.splitter);
    
    // Check for old settings (<= 0.2.1)
    var saveSettings = false;
    try
    {
        // Get old prefixes
        var _oldprefixes = sbiz.CleanSubject.Trim(
                sbiz.CleanSubject.prefs.getCharPref(
                    sbiz.CleanSubject.prefPrefixOld + sbiz.CleanSubject.prefStringPrefixes));
        if (_oldprefixes && _oldprefixes.length > 0)
        {
            var oldprefixes = _oldprefixes.split(sbiz.CleanSubject.splitter);
            for (var j = 0; j < oldprefixes.length; j++)
            {
                // for each old prefix: check if it already is in the new prefix (with and without :)
                if (!(sbiz.CleanSubject.ArrayContains(sbiz.CleanSubject.prefixes, oldprefixes[j])) &&
                    !(sbiz.CleanSubject.ArrayContains(sbiz.CleanSubject.prefixes, oldprefixes[j] + ":")))
                {
                    // Append it with a colon (if no colon is present at the end) 
                    var oldprefix = oldprefixes[j];
                    if (oldprefix.substr(oldprefix.length - 1) != ":")
                    {
                         oldprefix += ":";
                    }
                    sbiz.CleanSubject.prefixes[sbiz.CleanSubject.prefixes.length] = oldprefix;
                }
            }
            // Delete old preference
            (sbiz.CleanSubject.prefs).deleteBranch(sbiz.CleanSubject.prefPrefixOld + sbiz.CleanSubject.prefStringPrefixes);
            
            // Set flag to immediately save this new converted setting and display info
            saveSettings = true;
            alert(document.getElementById('extname-strings').getString("extensions.cleansubject@style-biz.de.alertSettingsConverted"));
        }
    }
    catch (e) {}
    
    // Create an item for each prefix
    for (var i = 0; i < sbiz.CleanSubject.prefixes.length; i++)
    {
        var trimmed = sbiz.CleanSubject.Trim(sbiz.CleanSubject.prefixes[i]);
        if (trimmed.length > 0)
        {
            sbiz.CleanSubject.Add(trimmed);
        }
    }
    
    // Set variables
    sbiz.CleanSubject.SetVariablesFromPreferences();
    
    // Enable it for forwarding?
    document.getElementById("cSforward").checked = sbiz.CleanSubject.forward;
    
    // Set reply and forward pre- and postfixes
    document.getElementById("cSreplyPrefix").value = sbiz.CleanSubject.replyPrefix;
    document.getElementById("cSreplyPostfix").value = sbiz.CleanSubject.replyPostfix;
    document.getElementById("cSforwardPrefix").value = sbiz.CleanSubject.forwardPrefix;
    document.getElementById("cSforwardPostfix").value = sbiz.CleanSubject.forwardPostfix;
    
    
    // Need to immediatelly save the settings?
    if (saveSettings)
    {
        sbiz.CleanSubject.SavePreferences();
    }
}

// Save the entered input and build the single string
sbiz.CleanSubject.SavePreferences = function()
{
    // save all textbox splitted by the splitter
    var stringToSave = "";
    var list = document.getElementsByTagName('textbox');
    for (var item = 0; item < list.length; item++)
    {
        if (list[item].getAttribute("class") == "prefix")
        {
            var trimmed = sbiz.CleanSubject.Trim(list[item].value);
            if ((trimmed.length > 0) && (typeof trimmed != 'undefined'))
            {
                stringToSave += trimmed + sbiz.CleanSubject.splitter;
            }
        }
    }
    sbiz.CleanSubject.prefs.setCharPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringPrefixes,
            stringToSave);
    
    // Save if enabled for forwarding
    if (document.getElementById("cSforward").checked)
    {
        sbiz.CleanSubject.prefs.setBoolPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringForward,
            true);
    }
    else
    {
        sbiz.CleanSubject.prefs.setBoolPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringForward,
            false);
    }
    
    // Save reply and forward pre- and postfixes
    sbiz.CleanSubject.prefs.setCharPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringReplyPrefix,
            document.getElementById("cSreplyPrefix").value);
    sbiz.CleanSubject.prefs.setCharPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringReplyPostfix,
            document.getElementById("cSreplyPostfix").value);
    sbiz.CleanSubject.prefs.setCharPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringForwardPrefix,
            document.getElementById("cSforwardPrefix").value);
    sbiz.CleanSubject.prefs.setCharPref(
            sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringForwardPostfix,
            document.getElementById("cSforwardPostfix").value);
    
    // Return true to close the dialog
    return true;
}

// Tests the settings on an arbitrary subject that can be
// specified in a test dialog in the settings
sbiz.CleanSubject.TestSubject = function()
{
    // Save the subject element ID so that it can be restored afterwards
    var _subjectIDBefore = sbiz.CleanSubject.subjectElementID;
    var _subjectResultIDBefore = sbiz.CleanSubject.subjectResultElementID;    
    
    // Set the test fields
    sbiz.CleanSubject.subjectElementID = "cStestSubjectHidden";
    sbiz.CleanSubject.subjectResultElementID = "cStestResult";
    
    // Prepend the Re:
    document.getElementById(sbiz.CleanSubject.subjectElementID).value = sbiz.CleanSubject.reply_prefix 
                + document.getElementById("cStestSubject").value;
    
    // Let it run!
    sbiz.CleanSubject.Init();
    
    // Reset the subject values we had before entering this function
    sbiz.CleanSubject.subjectElementID = _subjectIDBefore;
    sbiz.CleanSubject.subjectResultElementID = _subjectResultIDBefore;
}


// Set the reply/forward pre- and postfixes to the TB defaults
sbiz.CleanSubject.ResetDefaultPrefixes = function()
{
    document.getElementById("cSreplyPrefix").value = sbiz.CleanSubject.defaultReplyPrefix;
    document.getElementById("cSreplyPostfix").value = sbiz.CleanSubject.defaultReplyPostfix;
    document.getElementById("cSforwardPrefix").value = sbiz.CleanSubject.defaultForwardPrefix;
    document.getElementById("cSforwardPostfix").value = sbiz.CleanSubject.defaultForwardPostfix;
}

// Set the prefixes to be cleaned to the extensions default
sbiz.CleanSubject.SetExtensionDefaultPrefixes = function()
{     
    // Revert setting
    try
    {
        (sbiz.CleanSubject.prefs).clearUserPref(sbiz.CleanSubject.prefPrefix + sbiz.CleanSubject.prefStringPrefixes);
    }
    catch (e) {}
    
    // Close GUI
    self.close();
}

// Save the initial window height
sbiz.CleanSubject.SaveWindowHeight = function()
{
    if (sbiz.CleanSubject.beginHeight == null)
    {
        sbiz.CleanSubject.beginHeight = window.innerHeight;
    }
}

// Set a new height when it is not smaller than the init value
sbiz.CleanSubject.RecalculateWindowHeight = function(height)
{
    result = window.innerHeight;
    result += height;
    
    if (result >= sbiz.CleanSubject.beginHeight)
    {
        if (sbiz.CleanSubject.heightNotModifiedCounter > 0)
        {
            sbiz.CleanSubject.heightNotModifiedCounter--;
        }
        else
        {
            window.innerHeight = result;
        }
    }
    else
    {
        sbiz.CleanSubject.heightNotModifiedCounter++;
    }
}